package org.steven.crm.core.service.systemuser;

import org.steven.crm.core.exception.ServiceException;
import org.steven.crm.core.query.SystemRoleQueryDataList;
import org.steven.crm.core.service.BaseService;
import com.steven.xdb.dbmanager.DBManager;
import com.steven.xdb.pagination.query.AbstractQueryDataList;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @Author wuzw
 * @Date 2021/5/24 21:30
 * @Version 1.0
 */
public class SystemRoleService extends BaseService {
    private static final SystemRoleMenuService systemRoleMenuService = new SystemRoleMenuService();

    private static final SystemMenuService systemMenuService = new SystemMenuService();

    @Override
    protected String getTable() {
        return "systemRole";
    }

    @Override
    protected AbstractQueryDataList getQueryDataList() {
        return new SystemRoleQueryDataList();
    }

    @Override
    protected String getDataSourceName() {
        return null;
    }

    @Override
    public void beforeCreate(Map<String, String> data) throws Exception {
        super.beforeCreate(data);

        if (isExistsName("", data.get("name"))) {
            throw new ServiceException("角色名称已存在");
        }
    }

    @Override
    public void beforeUpdate(String id, Map<String, String> data) throws Exception {
        super.beforeUpdate(id, data);

        if (isExistsName(id, data.get("name"))) {
            throw new ServiceException("角色名称已存在");
        }
    }

    public List<Map<String, String>> readAllValid() throws Exception {
        Map<String, String> k = new HashMap<>();
        k.put("validFlag", "1");
        k.put("deleted", "0");

        return DBManager.query(getSession(), getTable(), k);
    }

    public Map<String, Object> readEx(String id) throws Exception {
        Map<String, Object> data = new HashMap<>();
        Map<String, String> role = read(id);
        if (role.isEmpty()) {
            throw new ServiceException("不存在该角色");
        }
        data.putAll(role);
        data.put("menuIds", getRoleMenuIds(id));

        return data;
    }

    public Map<String, Object> save(String id,
                     String name, Collection<String> menuIds) throws Exception {
        if (StringUtils.isEmpty(id)) {
            Map<String, String> data = new HashMap<>();
            data.put("name", name);
            Map<String, String> role = this.create(data);
            id = role.get("id");
        } else {
            Map<String, String> data = new HashMap<>();
            data.put("name", name);
            this.update(id, data);
        }


        List<String> tenantSupplierMenuIds = systemMenuService.readAllValidIds();
        Collection<String> validmenuIds = CollectionUtils.intersection(tenantSupplierMenuIds, menuIds);
        systemRoleMenuService.batchSave(id, validmenuIds);

        return readEx(id);
    }

    public Collection<String> getRoleMenuIds(String roleId) throws Exception {
        List<String> tenantSupplierMenuIds = systemMenuService.readAllValidIds();
        List<String> roleMenuIds = systemRoleMenuService.getRoleMenuIds(roleId);

        Collection<String> menuIds = CollectionUtils.intersection(tenantSupplierMenuIds, roleMenuIds);

        return menuIds;
    }

    public Collection<String> getRoleMenuIds(List<String> roleIds) throws Exception {
        List<String> supplierMenuIds = systemMenuService.readAllValidIds();
        List<String> roleMenuIds = systemRoleMenuService.getRoleMenuIds(roleIds);

        Collection<String> menuIds = CollectionUtils.intersection(supplierMenuIds, roleMenuIds);

        return menuIds;
    }

    public Collection<String> getSupperRoleMenuIds() throws Exception {
        List<String> supplierMenuIds = systemMenuService.readAllValidIds();

        return supplierMenuIds;
    }

    public Map<String, Map<String, String>> readByIdsMap(Collection<String> ids, String columns) throws Exception {
        if (ids == null || ids.size() == 0) {
            return new HashMap<>();
        }

        if (!columns.equals("*")) {
            List<String> columnsArrs = Arrays.asList(StringUtils.split(columns, ","));
            if (!columnsArrs.contains("id")) {
                columnsArrs.add("id");
                columns = String.join(",", columnsArrs);
            }
        }

        String sql = "select " + columns + " from " + getTable() + " where id in (" + String.join(",", ids) + ") and deleted = 0";
        List<Map<String, String>> datas = DBManager.query(getSession(), sql, new ArrayList<>());

        Map<String, Map<String, String>> result = new HashMap<>();
        for (Map<String, String> data : datas) {
            result.put(data.get("id"), data);
        }

        return result;
    }

    public boolean isExistsName(String id, String userName) throws Exception {
        Map<String, String> data = readByName(userName);
        return !data.isEmpty() && !data.get("id").equals(id);
    }

    public Map<String, String> readByName(String name) throws Exception {
        Map<String, String> k = new HashMap<>();
        k.put("name", name);
        k.put("deleted", "0");

        List<Map<String, String>> datas = DBManager.query(getSession(), getTable(), k);

        return datas.size() == 0 ? new HashMap<>() : datas.get(0);
    }
}
